// pages/api/articles/hot.ts
import { NextResponse } from 'next/server'
import { pool } from '../db'

export interface RecommendArticle {
  id: number
  title: string
  summary?: string
  author?: string
  publishTime?: Date
  viewCount?: number
  likeCount?: number
  commentCount?: number
  coverImage?: string
  tags: string[]
  categoryId: number
  categoryName: string[]
}

export interface QueryHotArticlesRequest {
  page?: number
  pageSize?: number
  categoryId?: number
  tag?: string
}

export interface QueryHotArticlesResponse {
  articles: RecommendArticle[]
  total: number
  page: number
  pageSize: number
}

export async function POST(req: Request) {
  try {
    const body = await req.json() // 修改为const
    const { page = 1, pageSize = 10 } = body // 修改为const

    const pageNum = parseInt(page as string)
    const size = parseInt(pageSize as string)
    const offset = (pageNum - 1) * size

    const client = await pool.getConnection()

    try {
      // 添加查询条件：push_status='publish' 以及 post_type='post' 或 post_type='cool_timeline'
      const query = `
     SELECT * 
     FROM wp_posts 
     WHERE post_status = 'publish' 
     AND (post_type = 'post' OR post_type = 'cool_timeline')
     ORDER BY post_date DESC 
     LIMIT ? OFFSET ?
     `
      const countQuery = `
     SELECT COUNT(*) as total
     FROM wp_posts
     WHERE post_status = 'publish' 
     AND (post_type = 'post' OR post_type = 'cool_timeline')
     `

      // 执行查询时传入分页参数
      const [result, countResult] = await Promise.all([
        client.query(query, [size, offset]),
        client.query(countQuery),
      ])
      return NextResponse.json(
        {
          data: result[0],
          total: countResult[0][0].total,
          page: pageNum,
          pageSize: size,
        },
        { status: 200 }
      )
    } finally {
      client.release()
    }
  } catch (error) {
    console.error('获取热门文章失败:', error)
    return NextResponse.json(
      {
        code: 500,
        message: '服务器内部错误',
        error: error instanceof Error ? error.message : 'Unknown error',
      },
      { status: 500 }
    )
  }
}

// 修复GET请求处理
export async function GET(req: Request) {
  try {
    const { searchParams } = new URL(req.url)
    const page = searchParams.get('page') || 1
    const pageSize = searchParams.get('pageSize') || 10

    const pageNum = parseInt(page as string)
    const size = parseInt(pageSize as string)
    const offset = (pageNum - 1) * size

    const client = await pool.getConnection()
    
    try {
      // 示例查询语句 - 注意：这里使用wp_hot_posts表，确保该表存在
      const query = `
     SELECT * 
     FROM wp_hot_posts 
     WHERE status = 1 
     ORDER BY publishTime DESC 
     LIMIT ? OFFSET ?
     `
      const countQuery = `
     SELECT COUNT(*) as total
     FROM wp_hot_posts
     WHERE status = 1
     `

      // 执行查询时传入分页参数
      const [result, countResult] = await Promise.all([
        client.query(query, [size, offset]),
        client.query(countQuery),
      ])
      
      return NextResponse.json(
        {
          data: result[0],
          total: countResult[0][0].total,
          page: pageNum,
          pageSize: size,
        },
        { status: 200 }
      )
    } finally {
      client.release()
    }
  } catch (error) {
    console.error('GET请求获取热门文章失败:', error)
    return NextResponse.json(
      {
        code: 500,
        message: '服务器内部错误',
        error: error instanceof Error ? error.message : 'Unknown error',
      },
      { status: 500 }
    )
  }
}
